﻿using Adaptive.Agrona;
using System;
using System.Collections.Generic;
using Unity.Connections;
using Unity.Type;
using Unity.Type.BinaryType;

namespace Unity.Client.Debug
{
    public class ConsoleUnityStreamProducer : IUnityProducer
    {
        private int counter = 0;
        private readonly Queue<IDirectBuffer> messages = new Queue<IDirectBuffer>();
        private readonly MetadataEDeserializer metadataDeserialize = new MetadataEDeserializer();
        // private readonly UnityStatisticsDeserializer = new UnityStatisticsDeserializer();
        public bool AddToBatching(IDirectBuffer buffer, int offset, int length)
        {
            this.counter++;
            Console.WriteLine($"Add to batching message #{this.counter}");
            this.messages.Enqueue(buffer);
            return true;
        }

        public int CompleteBatching()
        {
            int size = this.messages.Count;
           
            int count = 0;
            if(this.messages.Count > 0)
            {
                Console.WriteLine($"Run complete batching current queue of messages (size: {size})");
                while (this.messages.Count > 0)
                {
                    count++;
                    this.messages.Dequeue();
                }
                Console.WriteLine($"Complete batching current queue of messages (size: {size}, done: {count})");
            }
            
            return count;
        }

        public bool Produce(IDirectBuffer buffer, int offset, int length)
        {
            this.counter++;
            Console.WriteLine($"Produce message #{this.counter}");

            MetadataE metadata = this.metadataDeserialize.Deserialize(buffer.ByteArray);
            if(metadata != null)
            {
                Console.WriteLine(metadata.ToString());
            }
            
            
            return true;
        }

        public bool Connect()
        {
            return true;
        }

        public void Close()
        {
            // ignore
        }

        public void Dispose()
        {
            Close();
        }
    }
}
